/**
Nectarine Utility Project is a software interface for the web system 'demovibes'
Copyright (C) 2010  Alexandre LAURENT

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

website: http://code.google.com/p/nectarine-utility-project/
e-mail: lw.demoscene@gmail.com
**/

#include <QtGui/QApplication>

#ifndef QT_NO_DEBUG
    #include <QFile>
    #include <QByteArray>
#endif

#include <QDir>

#include "Interface/mainwindow.h"

#include "globals.h"

#ifndef QT_NO_DEBUG
QFile* pDebugFile = NULL;

void debugFileHandler(QtMsgType type, const char *msg)
{
    // Test to protect from some human errors (can be removed)
    if ( pDebugFile && pDebugFile->isOpen() )
    {
        switch (type)
        {
         case QtDebugMsg:
             pDebugFile->write(QByteArray(msg) + QByteArray("\n"));
             break;
         case QtWarningMsg:
             pDebugFile->write(QByteArray("Warning: ") + QByteArray(msg) + QByteArray("\n"));
             break;
         case QtCriticalMsg:
             pDebugFile->write(QByteArray("Critical: ") + QByteArray(msg) + QByteArray("\n"));
             break;
         case QtFatalMsg:
             pDebugFile->write(QByteArray("Fatal: ") + QByteArray(msg) + QByteArray("\n"));
             abort();
         }
    }
}
#endif


int main(int argc, char *argv[])
{
#ifndef QT_NO_DEBUG
    pDebugFile = new QFile("debug.log");
    pDebugFile->open(QIODevice::WriteOnly);
    // qInstallMsgHandler(debugFileHandler);
    qDebug() << "Log in file started";
#endif
    qDebug() << "Running in: " << QDir::currentPath();

    QApplication a(argc, argv);

    a.setApplicationName(APP_NAME);
    a.setOrganizationName(ORGANISATION);

    MainWindow w;
    int error = 0;

    // Load settings saved on the computer
    w.loadSettings();

    w.show();

    // Run
    error = a.exec();

    // Save new setting
    w.saveSettings();

#ifndef QT_NO_DEBUG
    qDebug() << "Log in file closed";
    pDebugFile->close();
    delete pDebugFile;
    pDebugFile = NULL;
    // Because of this, all deletion messages will not be seen in the debug file.
    // Thanks to this, we don't try to use a file closed
    qInstallMsgHandler(0);
#endif

    return error;
}
